<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频查看 - 老师端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .video-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .video-player-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .video-player {
            width: 100%;
            height: 500px;
            border-radius: 10px;
            background: #000;
            margin-bottom: 20px;
        }

        .video-info {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .video-title {
            font-size: 1.8em;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
        }

        .video-meta {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .meta-label {
            font-weight: 500;
            color: #666;
        }

        .meta-value {
            color: #333;
        }

        .video-description {
            color: #666;
            line-height: 1.6;
            margin-bottom: 20px;
        }

        .video-actions {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
            transform: translateY(-2px);
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .related-videos {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .section-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .video-list {
            display: grid;
            gap: 15px;
        }

        .video-item {
            display: flex;
            gap: 15px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .video-item:hover {
            background: #f8f9fa;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .video-thumbnail {
            width: 120px;
            height: 80px;
            background: #f0f0f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2em;
            color: #666;
        }

        .video-item-info {
            flex: 1;
        }

        .video-item-title {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .video-item-meta {
            font-size: 0.9em;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .error-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .error-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .error-description {
            font-size: 1em;
            line-height: 1.5;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <span class="brand-icon">🎓</span>
                <span class="brand-text">学习平台</span>
            </div>
            <div class="nav-menu">
                <a href="dashboard.html" class="nav-link">
                    <span class="nav-icon">🏠</span>
                    <span class="nav-text">首页</span>
                </a>
                <a href="videos.html" class="nav-link">
                    <span class="nav-icon">📹</span>
                    <span class="nav-text">视频管理</span>
                </a>
                <a href="exam-management.html" class="nav-link">
                    <span class="nav-icon">📝</span>
                    <span class="nav-text">考试管理</span>
                </a>
                <a href="question-management.html" class="nav-link">
                    <span class="nav-icon">❓</span>
                    <span class="nav-text">题目管理</span>
                </a>
                <a href="students.html" class="nav-link">
                    <span class="nav-icon">👥</span>
                    <span class="nav-text">学生管理</span>
                </a>
            </div>
            <div class="nav-user">
                <span class="user-info" id="userInfo">加载中...</span>
                <button class="btn-logout" onclick="logout()">退出</button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <h1 class="page-title">📹 视频查看</h1>
            <p class="page-subtitle">查看和管理视频内容</p>
        </div>

        <div id="loadingState" class="loading">
            <div class="loading-spinner"></div>
            <p>正在加载视频...</p>
        </div>

        <div id="errorState" class="error-state" style="display: none;">
            <div class="error-icon">❌</div>
            <h3 class="error-title">视频加载失败</h3>
            <p class="error-description" id="errorMessage">请检查视频是否存在或权限是否正确</p>
        </div>

        <div id="videoContent" class="video-container" style="display: none;">
            <div class="video-player-section">
                <video class="video-player" id="videoPlayer" controls>
                    <source id="videoSource" src="" type="video/mp4">
                    您的浏览器不支持视频播放。
                </video>
                
                <div class="video-actions">
                    <button class="btn-action btn-primary" onclick="editVideo()">
                        ✏️ 编辑视频
                    </button>
                    <button class="btn-action btn-success" onclick="approveVideo()">
                        ✅ 审核通过
                    </button>
                    <button class="btn-action btn-warning" onclick="rejectVideo()">
                        ❌ 审核拒绝
                    </button>
                    <button class="btn-action btn-secondary" onclick="downloadVideo()">
                        📥 下载视频
                    </button>
                    <button class="btn-action btn-danger" onclick="deleteVideo()">
                        🗑️ 删除视频
                    </button>
                </div>
            </div>

            <div class="video-info">
                <h2 class="video-title" id="videoTitle">视频标题</h2>
                
                <div class="video-meta">
                    <div class="meta-item">
                        <span class="meta-label">上传者:</span>
                        <span class="meta-value" id="uploaderName">未知</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">上传时间:</span>
                        <span class="meta-value" id="uploadTime">未知</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">观看次数:</span>
                        <span class="meta-value" id="viewCount">0</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">审核状态:</span>
                        <span class="meta-value" id="approvalStatus">未知</span>
                    </div>
                </div>

                <div class="video-description" id="videoDescription">
                    视频描述信息...
                </div>
            </div>
        </div>

        <div class="related-videos">
            <h2 class="section-title">相关视频</h2>
            <div class="video-list" id="relatedVideos">
                <!-- 相关视频列表将在这里动态生成 -->
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentVideo = null;
        let currentUser = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadVideo();
        });

        // 检查用户认证状态
        function checkAuth() {
            currentUser = UserManager.getCurrentUser();
            if (!currentUser || (currentUser.role !== 1 && currentUser.role !== 0)) {
                Message.error('请先登录老师或管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            document.getElementById('userInfo').textContent = `欢迎，${currentUser.name}`;
        }

        // 加载视频
        async function loadVideo() {
            const urlParams = new URLSearchParams(window.location.search);
            const videoId = urlParams.get('id');
            
            if (!videoId) {
                showError('视频ID不存在');
                return;
            }

            try {
                const response = await API.get(`/video/teacher/${videoId}`);
                if (response.success) {
                    currentVideo = response.video;
                    renderVideo();
                    loadRelatedVideos();
                } else {
                    showError(response.message || '视频加载失败');
                }
            } catch (error) {
                console.error('加载视频失败:', error);
                showError('视频加载失败，请稍后重试');
            }
        }

        // 渲染视频
        function renderVideo() {
            if (!currentVideo) return;

            // 设置视频源
            const videoPlayer = document.getElementById('videoPlayer');
            const videoSource = document.getElementById('videoSource');
            videoSource.src = `/videos/${currentVideo.path}`;
            videoPlayer.load();

            // 设置视频信息
            document.getElementById('videoTitle').textContent = currentVideo.title;
            document.getElementById('uploaderName').textContent = currentVideo.uploaderName || '未知';
            document.getElementById('uploadTime').textContent = formatDate(currentVideo.uploadTime);
            document.getElementById('viewCount').textContent = currentVideo.viewCount || 0;
            document.getElementById('approvalStatus').textContent = getApprovalStatusText(currentVideo.approved);
            document.getElementById('videoDescription').textContent = currentVideo.intro || '暂无描述';

            // 根据用户角色和视频状态显示/隐藏操作按钮
            updateActionButtons();

            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('videoContent').style.display = 'grid';
        }

        // 更新操作按钮
        function updateActionButtons() {
            const editBtn = document.querySelector('button[onclick="editVideo()"]');
            const approveBtn = document.querySelector('button[onclick="approveVideo()"]');
            const rejectBtn = document.querySelector('button[onclick="rejectVideo()"]');
            const deleteBtn = document.querySelector('button[onclick="deleteVideo()"]');

            // 只有视频上传者或管理员可以编辑和删除
            const canEdit = currentUser.role === 0 || currentVideo.uploaderId === currentUser.id;
            editBtn.style.display = canEdit ? 'inline-flex' : 'none';
            deleteBtn.style.display = canEdit ? 'inline-flex' : 'none';

            // 只有管理员可以审核
            const canApprove = currentUser.role === 0;
            approveBtn.style.display = canApprove ? 'inline-flex' : 'none';
            rejectBtn.style.display = canApprove ? 'inline-flex' : 'none';

            // 如果视频已审核通过，隐藏审核按钮
            if (currentVideo.approved === 1) {
                approveBtn.style.display = 'none';
                rejectBtn.style.display = 'none';
            }
        }

        // 加载相关视频
        async function loadRelatedVideos() {
            try {
                const response = await API.get('/video/teacher/related');
                if (response.success) {
                    renderRelatedVideos(response.videos || []);
                }
            } catch (error) {
                console.error('加载相关视频失败:', error);
            }
        }

        // 渲染相关视频
        function renderRelatedVideos(videos) {
            const relatedVideosContainer = document.getElementById('relatedVideos');
            
            if (videos.length === 0) {
                relatedVideosContainer.innerHTML = '<p style="text-align: center; color: #666;">暂无相关视频</p>';
                return;
            }

            relatedVideosContainer.innerHTML = videos.map(video => `
                <div class="video-item" onclick="viewVideo(${video.id})">
                    <div class="video-thumbnail">📹</div>
                    <div class="video-item-info">
                        <div class="video-item-title">${video.title}</div>
                        <div class="video-item-meta">
                            ${video.uploaderName || '未知'} • ${formatDate(video.uploadTime)} • ${video.viewCount || 0} 次观看
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 显示错误状态
        function showError(message) {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorState').style.display = 'block';
        }

        // 获取审核状态文本
        function getApprovalStatusText(approved) {
            switch (approved) {
                case 0: return '待审核';
                case 1: return '已通过';
                case 2: return '已拒绝';
                default: return '未知';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 编辑视频
        function editVideo() {
            window.location.href = `upload.html?id=${currentVideo.id}&mode=edit`;
        }

        // 审核通过
        async function approveVideo() {
            if (!confirm('确定要审核通过这个视频吗？')) {
                return;
            }

            try {
                const response = await API.put(`/video/admin/approve/${currentVideo.id}`, {});
                if (response.success) {
                    Message.success('视频审核通过');
                    currentVideo.approved = 1;
                    updateActionButtons();
                    document.getElementById('approvalStatus').textContent = '已通过';
                } else {
                    Message.error(response.message || '审核失败');
                }
            } catch (error) {
                console.error('审核视频失败:', error);
                Message.error('审核失败，请稍后重试');
            }
        }

        // 审核拒绝
        async function rejectVideo() {
            const reason = prompt('请输入拒绝原因：');
            if (!reason) return;

            try {
                const response = await API.put(`/video/admin/reject/${currentVideo.id}`, {
                    reason: reason
                });
                if (response.success) {
                    Message.success('视频审核拒绝');
                    currentVideo.approved = 2;
                    updateActionButtons();
                    document.getElementById('approvalStatus').textContent = '已拒绝';
                } else {
                    Message.error(response.message || '审核失败');
                }
            } catch (error) {
                console.error('审核视频失败:', error);
                Message.error('审核失败，请稍后重试');
            }
        }

        // 下载视频
        function downloadVideo() {
            const link = document.createElement('a');
            link.href = `/videos/${currentVideo.path}`;
            link.download = currentVideo.title + '.mp4';
            link.click();
        }

        // 删除视频
        async function deleteVideo() {
            if (!confirm('确定要删除这个视频吗？删除后无法恢复。')) {
                return;
            }

            try {
                const response = await API.delete(`/video/delete/${currentVideo.id}`);
                if (response.success) {
                    Message.success('视频删除成功');
                    setTimeout(() => {
                        window.location.href = 'videos.html';
                    }, 1500);
                } else {
                    Message.error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除视频失败:', error);
                Message.error('删除失败，请稍后重试');
            }
        }

        // 查看视频
        function viewVideo(videoId) {
            window.location.href = `video-viewer.html?id=${videoId}`;
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                UserManager.logout();
                window.location.href = '../login.html';
            }
        }
    </script>
</body>
</html>
